package com.woohua.thread.wait;

/***
 * @title Producer
 * @description： 生产者
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/9 13:46
 **/
public class Producer implements Runnable {

    private TaskQueue taskQueue;

    public Producer(TaskQueue taskQueue) {
        this.taskQueue = taskQueue;
    }


    @Override
    public void run() {
        while (true) {
            generateTask();
            sleep(2000);
        }
    }

    /**
     * 生成任务
     */
    private void generateTask() {
        System.out.println("Producer generateTask()");
        int taskNum = (int) (5 * Math.random() + 1);
        long timestamp = System.currentTimeMillis();
        for (int i = 0; i < taskNum; i++) {
            String task = "Task_" + timestamp + "_" + i;
            taskQueue.addTask(task);
        }
    }

    /**
     * 休眠
     *
     * @param time 休眠时长
     */
    private void sleep(long time) {
        System.out.println("Producer sleep()");
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
